package com.yuanfeng.goods.util.es;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
@RefreshScope
public class ElasticSearchConfig {


    /**
     * 协议
     */
    @Value("${es.schema:http}")
    private String schema;
    /**
     * 集群地址，如果有多个用“,”隔开
     */
    @Value("${es.address}")
    private String address;
    /**
     * 集群地址，如果有多个用“,”隔开
     */
    @Value("${es.userName}")
    private String userName;
    /**
     * 集群地址，如果有多个用“,”隔开
     */
    @Value("${es.password}")
    private String password;
    /**
     * 连接超时时间
     */
    @Value("${es.connectTimeout}")
    private int connectTimeout;
    /**
     * Socket 连接超时时间
     */
    @Value("${es.socketTimeout}")
    private int socketTimeout;
    /**
     * 获取连接的超时时间
     */
    @Value("${es.connectionRequestTimeout}")
    private int connectionRequestTimeout;
    /**
     * 最大连接数
     */
    @Value("${es.maxConnectNum}")
    private int maxConnectNum;
    /**
     * 最大路由连接数
     */
    @Value("${es.maxConnectPerRoute}")
    private int maxConnectPerRoute;
    private RestHighLevelClient restHighLevelClient;

    /**
     * 批量操作的对象
     */
    private static BulkProcessor bulkProcessor;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials elastic = new UsernamePasswordCredentials(userName, password);
        credentialsProvider.setCredentials(AuthScope.ANY,elastic);
        // 拆分地址
        List<HttpHost> hostLists = new ArrayList<>();
        String[] hostList = address.split(",");
        for (String addr : hostList) {
            String host = addr.split(":")[0];
            String port = addr.split(":")[1];
            hostLists.add(new HttpHost(host, Integer.parseInt(port), schema));
        }
        // 转换成 HttpHost 数组
        HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
        // 构建连接对象
        RestClientBuilder builder = RestClient.builder(httpHost);
        // 异步连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeout);
            requestConfigBuilder.setSocketTimeout(socketTimeout);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
            return requestConfigBuilder;
        });
        // 异步连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        });
        restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }
    @PreDestroy
    public void clientClose() {
        try {
            this.restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
